package com.quanxiaoha.weblog.admin.validator;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

/**
 * @author: 犬小哈
 * @url: www.quanxiaoha.com
 * @date: 2025-01-20
 * @description: 条件验证器实现
 **/
@Slf4j
public class ConditionalValidator implements ConstraintValidator<ConditionalValidation, Object> {

    private String conditionField;
    private String conditionValue;
    private String[] requiredFields;
    private String[] messages;

    @Override
    public void initialize(ConditionalValidation constraintAnnotation) {
        this.conditionField = constraintAnnotation.conditionField();
        this.conditionValue = constraintAnnotation.conditionValue();
        this.requiredFields = constraintAnnotation.requiredFields();
        this.messages = constraintAnnotation.messages();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            // 获取条件字段的值
            Field conditionFieldObj = value.getClass().getDeclaredField(conditionField);
            conditionFieldObj.setAccessible(true);
            Object conditionFieldValue = conditionFieldObj.get(value);

            // 如果条件不满足，则不进行验证
            if (!conditionValue.equals(String.valueOf(conditionFieldValue))) {
                return true;
            }

            // 如果条件满足，验证必需字段
            boolean isValid = true;
            context.disableDefaultConstraintViolation();

            for (int i = 0; i < requiredFields.length; i++) {
                String fieldName = requiredFields[i];
                String message = i < messages.length ? messages[i] : "字段 " + fieldName + " 不能为空";

                Field field = value.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object fieldValue = field.get(value);

                // 检查字段是否为空
                boolean fieldIsEmpty = false;
                if (fieldValue == null) {
                    fieldIsEmpty = true;
                } else if (fieldValue instanceof String && !StringUtils.hasText((String) fieldValue)) {
                    fieldIsEmpty = true;
                }

                if (fieldIsEmpty) {
                    context.buildConstraintViolationWithTemplate(message)
                            .addPropertyNode(fieldName)
                            .addConstraintViolation();
                    isValid = false;
                }
            }

            return isValid;

        } catch (Exception e) {
            log.error("条件验证器执行异常", e);
            return false;
        }
    }
}
